<template>
  <BasicDrawer v-bind="$attrs" @register="register" :title="displayModuleTitle" width="90%">
    <BasicTable
      @register="registerTable"
      :indentSize="30"
      :loading="false"
      :ellipsis="true"
      :searchInfo="searchInfo"
      :pagination="false"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddCategoryButtonClick">新增危险源类别</a-button>
        <a-button type="primary" @click="onImportTemplateHazardButtonClick">导入</a-button>
      </template>
      <template #ismajor="{ record }">
        <template v-if="record.ismajor">
          <Tag :color="'red'">是</Tag>
        </template>
        <template v-else-if="record.ismajor === false">
          <Tag :color="'green'">否</Tag>
        </template>
        <template v-else-if="record.ismajor === null"> - </template>
      </template>
      <template #tags="{ record }">
        <template v-if="record.tags">
          <Tag color="blue">
            {{
              hazardTagOption.filter((item) => item.value == record.tags).length > 0
                ? hazardTagOption.filter((item) => item.value == record.tags)[0].label
                : record.tags
            }}</Tag
          >
        </template>
        <template v-else>-</template>
      </template>
      <template #LData="{ record }">
        {{ record.lmin || record.lmax ? record.lmin + '~' + record.lmax : '-' }}
      </template>
      <template #EData="{ record }">
        {{ record.emin || record.emax ? record.emin + '~' + record.emax : '-' }}
      </template>
      <template #CData="{ record }">
        {{ record.cmin || record.cmax ? record.cmin + '~' + record.cmax : '-' }}
      </template>
      <template #action="{ column, record }">
        <TableAction
          v-if="record.level != 3"
          :actions="[
            {
              icon: 'clarity:add-line',
              tooltip: `在此${record.level == 1 ? '类别下新增项目' : '项目下新增清单'}`,
              onClick: onAddButtonClick.bind(null, record),
            },
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑',
              onClick: onEditButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              tooltip: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: onDeleteButtonClick.bind(null, record),
              },
            },
          ]"
        />
        <TableAction
          v-if="record.level == 3"
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑',
              onClick: onEditButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: onDeleteButtonClick.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <ImportTemplateHazard @register="registerImportTemplateHazardModal" @success="opSuccess" />
    <AddOrUpdateCategory @register="registerAddOrUpdateCategoryModal" @success="opSuccess" />
    <AddOrUpDateProject @register="registerAddOrUpdateProjectModal" @success="opSuccess" />
    <AddOrUpDateItem @register="registerAddOrUpdateItemModal" @success="opSuccess" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref, onMounted } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTable, TableAction, useTable } from '/@/components/Table/index';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import {
    queryDangerDbTreeList,
    deleteCategory,
    deleteProject,
    deleteItem,
  } from '/@/api/ehs/templateHazard';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { TplHazardTreeTableItemDto } from '/@/api/ehs/model/templateHazardModel';
  import {
    hazardListTableColumns,
    queryHazardsListConditionFormSchema,
  } from './templateHazard.data';
  import ImportTemplateHazard from './ImportTemplateHazard.vue';
  import AddOrUpdateCategory from './AddOrUpdateCategory.vue';
  import AddOrUpDateProject from './AddOrUpdateProject.vue';
  import AddOrUpDateItem from './AddOrUpDateItem.vue';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { Tag } from 'ant-design-vue';
  export default defineComponent({
    name: 'ViewHazardsList',
    components: {
      BasicDrawer,
      Tag,
      BasicTable,
      TableAction,
      ImportTemplateHazard,
      AddOrUpdateCategory,
      AddOrUpDateProject,
      AddOrUpDateItem,
    },
    setup(_, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const searchInfo = ref({
        hdbcd: '',
      });
      const hazardTagOption = ref([]);
      const [registerImportTemplateHazardModal, { openModal: openImportTemplateHazard }] =
        useModal();
      const [registerAddOrUpdateCategoryModal, { openModal: openAddOrUpdateCategory }] = useModal();
      const [registerAddOrUpdateProjectModal, { openModal: openAddOrUpdateProject }] = useModal();
      const [registerAddOrUpdateItemModal, { openModal: openAddOrUpdateItem }] = useModal();
      const { createMessage } = useMessage();
      const [registerTable, { setTableData, getForm, reload }] = useTable({
        api: queryDangerDbTreeList,
        columns: hazardListTableColumns,
        canResize: true,
        immediate: true,
        bordered: true,
        ellipsis: true,
        striped: false,
        showTableSetting: true,
        indexColumnProps: {
          width: 50,
        },
        isTreeTable: true,
        useSearchForm: true,
        formConfig: {
          labelWidth: 100,
          schemas: queryHazardsListConditionFormSchema,
          autoSubmitOnEnter: true,
        },
        tableSetting: {
          redo: false,
        },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      const [register, { closeDrawer }] = useDrawerInner((data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.dataId) {
            searchInfo.value.hdbcd = unrefData.dataId;
            reload();
          }
        }
        queryEnumOptions('EhsHazardKeyTypeEnum,EhsHazardCategoryTypeEnum').then((res) => {
          // console.log('option res', res);
          if (res != undefined && res != null && res.length > 0x0) {
            const value1 = res[0].options.map((option) => {
              return {
                value: Number(option.key),
                label: option.value,
              };
            });
            const value2 = res[1].options.map((option) => {
              return {
                value: option.key,
                label: option.value,
              };
            });
            hazardTagOption.value = value2;
            getForm().updateSchema([
              {
                field: 'keytype',
                componentProps: {
                  options: value1,
                },
              },
              {
                field: 'tags',
                componentProps: {
                  options: value2,
                },
              },
            ]);
          }
        });
      });
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      function opSuccess() {
        reload();
      }
      function onImportTemplateHazardButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源导则库',
          operateString: '导入危险源清单',
          dataId: searchInfo.value.hdbcd,
        };
        openImportTemplateHazard(true, propsData);
      }
      function onAddButtonClick(record: TplHazardTreeTableItemDto) {
        if (record.level == 1) {
          // 新增分类下的项目
          let propsData: QcUnifyTransToChildProps = {
            moduleName: '危险源导则库',
            operateString: '新增危险源项目',
            operateType: OperationTypeEnum.ADD,
            hcatcd: record.code,
          };
          openAddOrUpdateProject(true, propsData);
        }
        if (record.level == 2) {
          // 新增项目下的危险源
          let propsData: QcUnifyTransToChildProps = {
            moduleName: '危险源导则库',
            operateString: '新增危险源清单',
            operateType: OperationTypeEnum.ADD,
            hpjtcd: record.code,
          };
          openAddOrUpdateItem(true, propsData);
        }
      }
      function onEditButtonClick(record: TplHazardTreeTableItemDto) {
        if (record.level == 1) {
          // 修改分类
          let propsData: QcUnifyTransToChildProps = {
            moduleName: '危险源导则库',
            operateString: '修改危险源类别',
            operateType: OperationTypeEnum.EDIT,
            dataId: record.code,
          };
          openAddOrUpdateCategory(true, propsData);
        }
        if (record.level == 2) {
          // 修改项目
          let propsData: QcUnifyTransToChildProps = {
            moduleName: '危险源导则库',
            operateString: '修改危险源项目',
            operateType: OperationTypeEnum.EDIT,
            dataId: record.code,
          };
          openAddOrUpdateProject(true, propsData);
        }
        if (record.level == 3) {
          //修改危险源
          let propsData: QcUnifyTransToChildProps = {
            moduleName: '危险源导则库',
            operateString: '修改危险源清单',
            operateType: OperationTypeEnum.EDIT,
            dataId: record.code,
          };
          openAddOrUpdateItem(true, propsData);
        }
      }
      function onDeleteButtonClick(record: TplHazardTreeTableItemDto) {
        if (record.level == 1) {
          // 删除分类
          deleteCategory(record.code)
            .then((res) => {
              console.log('res', res);
              //res判断结果：同时==undefined和null
              if (res == undefined && (res == null || Object.keys(res).length == 0)) {
                createMessage.success('删除成功。', 2);
                opSuccess();
              }
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        }
        if (record.level == 2) {
          // 删除项目
          deleteProject(record.code)
            .then((res) => {
              console.log('res', res);
              //res判断结果：同时==undefined和null
              if (res == undefined && (res == null || Object.keys(res).length == 0)) {
                createMessage.success('删除成功。', 2);
                opSuccess();
              }
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        }
        if (record.level == 3) {
          //删除危险源
          deleteItem(record.code)
            .then((res) => {
              console.log('res', res);
              //res判断结果：同时==undefined和null
              if (res == undefined && (res == null || Object.keys(res).length == 0)) {
                createMessage.success('删除成功。', 2);
                opSuccess();
              }
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        }
      }
      function onAddCategoryButtonClick() {
        //新增分类
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '危险源导则库',
          operateString: '新增危险源类别',
          operateType: OperationTypeEnum.ADD,
          hdbcd: searchInfo.value.hdbcd,
        };
        openAddOrUpdateCategory(true, propsData);
      }
      onMounted(() => {});
      return {
        hazardTagOption,
        register,
        closeDrawer,
        displayModuleTitle,
        opSuccess,
        registerTable,
        searchInfo,
        registerImportTemplateHazardModal,
        onImportTemplateHazardButtonClick,
        onEditButtonClick,
        onAddButtonClick,
        onDeleteButtonClick,
        onAddCategoryButtonClick,
        registerAddOrUpdateCategoryModal,
        registerAddOrUpdateProjectModal,
        registerAddOrUpdateItemModal,
      };
    },
  });
</script>
